<template>
	<view class="add-address-container">
		<!-- 自定义导航栏 -->
		<u-navbar
			:title="isEdit ? '修改收货地址' : '新增收货地址'"
			:autoBack="true"
			bgColor="#ffffff"
			:fixed="true"
			:placeholder="true"
			:safeAreaInsetTop="true"
		></u-navbar>
		
		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 收货人 -->
			<view class="form-item">
				<text class="form-label">收货人</text>
				<input 
					class="form-input" 
					type="text" 
					v-model="addressForm.name" 
					placeholder="请输入收货人姓名"
				/>
			</view>
			
			<!-- 手机号 -->
			<view class="form-item">
				<text class="form-label">手机号</text>
				<input 
					class="form-input" 
					type="number" 
					v-model="addressForm.phone" 
					placeholder="请输入手机号"
					maxlength="11"
				/>
			</view>
			
			<!-- 所在地区（小程序端使用原生 region 选择器，H5 使用 u-picker 级联选择） -->
			<!-- #ifdef MP -->
			<picker mode="region" @change="onRegionChange">
				<view class="form-item">
					<text class="form-label">所在地区</text>
					<view class="region-picker">
						<text v-if="addressForm.province" class="region-text">
							{{addressForm.province}} {{addressForm.city}} {{addressForm.district}}
						</text>
						<text v-else class="placeholder-text">请选择所在地区</text>
						<u-icon name="arrow-right" size="32rpx" color="#c0c4cc"></u-icon>
					</view>
				</view>
			</picker>
			<!-- #endif -->

			<!-- #ifdef H5 -->
			<view class="form-item" @click="openRegionPicker">
				<text class="form-label">所在地区</text>
				<view class="region-picker">
					<text v-if="addressForm.province" class="region-text">
						{{addressForm.province}} {{addressForm.city}} {{addressForm.district}}
					</text>
					<text v-else class="placeholder-text">请选择所在地区</text>
					<u-icon name="arrow-right" size="32rpx" color="#c0c4cc"></u-icon>
				</view>
			</view>
			<u-picker
				ref="regionPicker"
				:show="showPicker"
				:title="'选择所在地区'"
				:columns="pickerColumns"
				:defaultIndex="pickerIndex"
				@close="showPicker=false"
				@cancel="showPicker=false"
				@change="onPickerChange"
				@confirm="onPickerConfirm"
			></u-picker>
			<!-- #endif -->
			
			<!-- 详细地址 -->
			<view class="form-item address-detail-item">
				<text class="form-label">详细地址</text>
				<view class="address-detail-input">
					<textarea 
						v-model="addressForm.detailAddress" 
						placeholder="街道、门牌号等，5-50字" 
						class="detail-textarea"
						maxlength="50"
					></textarea>
					<view class="location-btn" @click="getLocation">
						<u-icon name="map" size="32rpx" color="#ff5722"></u-icon>
						<text class="location-text">定位</text>
					</view>
				</view>
			</view>
			
			<!-- 设为默认地址 -->
			<view class="form-item default-item">
				<text class="form-label">设为默认地址</text>
				<u-switch v-model="addressForm.isDefault" activeColor="#ff5722"></u-switch>
			</view>
		</view>
		
		<!-- 保存按钮 -->
		<view class="save-btn">
			<u-button 
				type="primary" 
				text="保存" 
				@click="saveAddress"
				shape="circle"
			></u-button>
		</view>
		
		<!-- 地区选择器改用原生picker，无需此组件 -->
	</view>
</template>

<script>
import { post, get, put } from '@/utils/request'
import { getUserId, isLoggedIn, goToLogin } from '@/utils/auth'

export default {
	data() {
		return {
			isEdit: false, // 是否为编辑模式
			addressId: null, // 编辑的地址ID
			showPicker: false, // 是否显示地区选择器（H5）
			regionTree: [], // 行政区树（H5）
			pickerColumns: [[], [], []], // u-picker 三列数据（H5）
			pickerIndex: [0, 0, 0], // u-picker 三列索引（H5）
			addressForm: {
				name: '',
				phone: '',
				province: '',
				city: '',
				district: '',
				detailAddress: '',
				isDefault: false
			}
		}
	},
	onLoad(options) {
		// 检查是否为编辑模式
		if (options.id) {
			this.isEdit = true;
			this.addressId = options.id;
			this.getAddressDetail(options.id);
		}
	},
	methods: {
		// 获取地址详情（编辑模式）
		async getAddressDetail(id) {
			try {
				const res = await get(`/address/${id}`);
				const data = res?.data || res || {};
				this.addressForm = {
					name: data.userName || '',
					phone: data.phone || '',
					province: data.province || '',
					city: data.city || '',
					district: data.county || '',
					detailAddress: data.content || '',
					isDefault: false
				};
			} catch (e) {
				uni.showToast({ title: '获取地址详情失败', icon: 'none' });
			}
		},
		
		// 原生地区选择器回调
		onRegionChange(e) {
			const vals = e.detail.value || [];
			this.addressForm.province = vals[0] || '';
			this.addressForm.city = vals[1] || '';
			this.addressForm.district = vals[2] || '';
		},

		// H5：打开地区选择器
		openRegionPicker() {
			// #ifdef H5
			if (!this.regionTree || this.regionTree.length === 0) {
				this.loadRegionData().then(() => {
					this.syncPickerIndexFromForm();
					this.showPicker = true;
				});
			} else {
				this.syncPickerIndexFromForm();
				this.showPicker = true;
			}
			// #endif
		},

		// H5：加载省市区数据（来自公开数据源）
		async loadRegionData() {
			return new Promise((resolve) => {
				uni.showLoading({ title: '加载地区数据...' });
				uni.request({
					url: 'https://unpkg.com/element-china-area-data@5/dist/area.json',
					method: 'GET',
					success: (res) => {
						const data = Array.isArray(res.data) ? res.data : [];
						this.regionTree = data;
						this.initPickerColumns();
					},
					fail: () => {
						uni.showToast({ title: '地区数据加载失败', icon: 'none' });
					},
					complete: () => {
						uni.hideLoading();
						resolve();
					}
				});
			});
		},

		// H5：初始化三级列
		initPickerColumns() {
			if (!this.regionTree.length) {
				this.pickerColumns = [[], [], []];
				return;
			}
			const provinces = this.regionTree.map(p => p.label || p.name || '');
			const firstProvince = this.regionTree[0] || {};
			const cities = (firstProvince.children || []).map(c => c.label || c.name || '');
			const firstCity = (firstProvince.children || [])[0] || {};
			const districts = (firstCity.children || []).map(d => d.label || d.name || '');
			this.pickerColumns = [provinces, cities, districts];
		},

		// H5：根据当前已选省市区，同步默认索引
		syncPickerIndexFromForm() {
			let pIndex = 0, cIndex = 0, dIndex = 0;
			if (!this.regionTree.length) { this.pickerIndex = [0,0,0]; return; }
			// 省
			const pList = this.regionTree;
			pIndex = Math.max(0, pList.findIndex(p => (p.label||p.name) === this.addressForm.province));
			if (pIndex === -1) pIndex = 0;
			const cList = (pList[pIndex]?.children) || [];
			cIndex = Math.max(0, cList.findIndex(c => (c.label||c.name) === this.addressForm.city));
			if (cIndex === -1) cIndex = 0;
			const dList = (cList[cIndex]?.children) || [];
			dIndex = Math.max(0, dList.findIndex(d => (d.label||d.name) === this.addressForm.district));
			if (dIndex === -1) dIndex = 0;
			// 同步列数据
			this.pickerColumns[0] = pList.map(p => p.label || p.name || '');
			this.pickerColumns[1] = cList.map(c => c.label || c.name || '');
			this.pickerColumns[2] = dList.map(d => d.label || d.name || '');
			this.pickerIndex = [pIndex, cIndex, dIndex];
			// 同步到组件
			this.$nextTick(() => {
				const picker = this.$refs.regionPicker;
				if (picker && picker.setIndexs) picker.setIndexs(this.pickerIndex, true);
			});
		},

		// H5：u-picker列变更
		onPickerChange({ columnIndex, indexs }) {
			const picker = this.$refs.regionPicker;
			if (!this.regionTree.length || !picker) return;
			let [pIndex, cIndex] = indexs;
			if (columnIndex === 0) {
				// 省改变，重置城市和区
				const cities = (this.regionTree[pIndex]?.children || []).map(c => c.label || c.name || '');
				picker.setColumnValues(1, cities);
				const firstCityChildren = (this.regionTree[pIndex]?.children || [])[0]?.children || [];
				picker.setColumnValues(2, firstCityChildren.map(d => d.label || d.name || ''));
			} else if (columnIndex === 1) {
				// 市改变，重置区
				const districts = (this.regionTree[pIndex]?.children || [])[cIndex]?.children || [];
				picker.setColumnValues(2, districts.map(d => d.label || d.name || ''));
			}
		},

		// H5：确认选择
		onPickerConfirm({ value, indexs }) {
			const [p, c, d] = value || [];
			this.addressForm.province = p || '';
			this.addressForm.city = c || '';
			this.addressForm.district = d || '';
			this.pickerIndex = indexs || [0,0,0];
			this.showPicker = false;
		},
		
		// 获取当前位置
		getLocation() {
			uni.showLoading({
				title: '定位中...'
			});
			
			// 调用定位API
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					// 根据经纬度获取详细地址
					this.getAddressByLocation(res.longitude, res.latitude);
				},
				fail: () => {
					uni.hideLoading();
					uni.showToast({
						title: '定位失败，请手动填写',
						icon: 'none'
					});
				}
			});
		},
		
		// 根据经纬度获取详细地址（模拟）
		getAddressByLocation(longitude, latitude) {
			// 实际项目中应该调用地图API获取详细地址
			// 这里使用模拟数据
			setTimeout(() => {
				uni.hideLoading();
				
				// 模拟返回的地址信息
				this.addressForm.province = '广东省';
				this.addressForm.city = '深圳市';
				this.addressForm.district = '南山区';
				this.addressForm.detailAddress = '科技园路1号';
				
				uni.showToast({
					title: '定位成功',
					icon: 'success'
				});
			}, 1000);
		},
		
		// 保存地址
		async saveAddress() {
			// 表单验证
			if (!this.validateForm()) {
				return;
			}
			
			// 显示加载中
			uni.showLoading({
				title: '保存中...'
			});
			
			try {
				if (!isLoggedIn()) { uni.hideLoading(); goToLogin(); return; }
				const stored = getUserId();
				const userIdNum = Number(stored);
				if (Number.isNaN(userIdNum)) {
					uni.hideLoading();
					uni.showToast({ title: '未获取到用户ID，请重新登录', icon: 'none' });
					return;
				}
				const payload = {
					province: this.addressForm.province,
					city: this.addressForm.city,
					county: this.addressForm.district,
					content: this.addressForm.detailAddress,
					userName: this.addressForm.name,
					phone: this.addressForm.phone
				};
				if (this.isEdit) {
					await put('/address', { id: this.addressId, ...payload });
				} else {
					await post('/address', payload);
				}
				uni.hideLoading();
				uni.showToast({ title: this.isEdit ? '修改成功' : '添加成功', icon: 'success' });
				setTimeout(() => { uni.navigateBack(); }, 1000);
			} catch (e) {
				uni.hideLoading();
				uni.showToast({ title: '保存失败', icon: 'none' });
			}
		},
		
		// 表单验证
		validateForm() {
			if (!this.addressForm.name) {
				uni.showToast({
					title: '请输入收货人姓名',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.addressForm.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return false;
			}
			
			if (!/^1\d{10}$/.test(this.addressForm.phone)) {
				uni.showToast({
					title: '手机号格式不正确',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.addressForm.province) {
				uni.showToast({
					title: '请选择所在地区',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.addressForm.detailAddress) {
				uni.showToast({
					title: '请输入详细地址',
					icon: 'none'
				});
				return false;
			}
			
			return true;
		}
	}
}
</script>

<style lang="scss" scoped>
.add-address-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.form-section {
	background-color: #ffffff;
	margin-top: 20rpx;
}

.form-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1px solid #f0f0f0;
}

.form-label {
	width: 180rpx;
	font-size: 28rpx;
	color: #333;
}

.form-input {
	flex: 1;
	height: 60rpx;
	font-size: 28rpx;
}

.region-picker {
	flex: 1;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.region-text {
	font-size: 28rpx;
	color: #333;
}

.placeholder-text {
	font-size: 28rpx;
	color: #c0c4cc;
}

.address-detail-item {
	align-items: flex-start;
}

.address-detail-input {
	flex: 1;
	position: relative;
}

.detail-textarea {
	width: 100%;
	height: 160rpx;
	font-size: 28rpx;
	line-height: 1.5;
}

.location-btn {
	position: absolute;
	right: 0;
	bottom: 0;
	display: flex;
	align-items: center;
	padding: 10rpx;
}

.location-text {
	font-size: 24rpx;
	color: #ff5722;
	margin-left: 6rpx;
}

.default-item {
	justify-content: space-between;
}

.save-btn {
	position: fixed;
	bottom: 30rpx;
	left: 30rpx;
	right: 30rpx;
}
</style>